<template>
  <div class="order-detail">
    <div class="page-header">
      <el-button @click="$router.go(-1)" icon="ArrowLeft">返回</el-button>
      <h1>订单详情</h1>
    </div>

    <el-card v-if="order" class="order-card">
      <!-- 订单状态 -->
      <div class="order-status">
        <el-steps :active="getStatusStep(order.status)" finish-status="success">
          <el-step title="已预约" description="等待支付"></el-step>
          <el-step title="已支付" description="等待确认"></el-step>
          <el-step title="已确认" description="准备拍摄"></el-step>
          <el-step title="拍摄中" description="进行中"></el-step>
          <el-step title="已完成" description="订单完成"></el-step>
        </el-steps>
      </div>

      <!-- 订单信息 -->
      <div class="order-info">
        <el-row :gutter="30">
          <el-col :span="12">
            <h3>订单信息</h3>
            <div class="info-item">
              <span class="label">订单号：</span>
              <span class="value">{{ order.id }}</span>
            </div>
            <div class="info-item">
              <span class="label">订单状态：</span>
              <el-tag :type="getStatusType(order.status)">
                {{ getStatusText(order.status) }}
              </el-tag>
            </div>
            <div class="info-item">
              <span class="label">拍摄套餐：</span>
              <span class="value">{{ order.packageName }}</span>
            </div>
            <div class="info-item">
              <span class="label">拍摄时间：</span>
              <span class="value">{{ formatDateTime(order.shootingTime) }}</span>
            </div>
            <div class="info-item">
              <span class="label">拍摄地点：</span>
              <span class="value">{{ order.shootingLocation }}</span>
            </div>
            <div class="info-item">
              <span class="label">订单金额：</span>
              <span class="value price">¥{{ order.totalPrice }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ formatDateTime(order.createTime) }}</span>
            </div>
          </el-col>
          
          <el-col :span="12">
            <h3>摄影师信息</h3>
            <div class="photographer-card">
              <img :src="order.photographer?.avatar" class="photographer-avatar" />
              <div class="photographer-info">
                <h4>{{ order.photographer?.name }}</h4>
                <p>{{ order.photographer?.style }}</p>
                <p>{{ order.photographer?.phone }}</p>
                <el-button 
                  v-if="['CONFIRMED', 'IN_PROGRESS', 'COMPLETED','PENDING'].includes(order.status)" 
                  type="primary" 
                  @click="startChat(order.id)"
                >
                  联系摄影师
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 订单操作 -->
      <div class="order-actions">
        <h3>订单操作</h3>
        <div class="action-buttons">
          <el-button 
            v-if="order.status === 'PENDING'" 
            type="primary" 
            size="large"
            @click="handlePay"
          >
            立即支付
          </el-button>
          <el-button 
            v-if="order.status === 'PENDING'" 
            type="danger" 
            size="large"
            @click="cancelOrder"
          >
            取消订单
          </el-button>
          <el-button 
            v-if="order.status === 'IN_PROGRESS' && isPhotographer" 
            type="success" 
            size="large"
            @click="completeOrder"
            :loading="completeLoading"
          >
            完成订单
          </el-button>
          <el-button 
            v-if="order.status === 'COMPLETED'" 
            type="success" 
            size="large"
            @click="viewPhotos"
          >
            查看照片
          </el-button>
          <el-button 
            v-if="order.status === 'COMPLETED'" 
            type="warning" 
            size="large"
            @click="rateOrder"
          >
            评价订单
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 支付对话框 -->
    <el-dialog v-model="payDialogVisible" title="订单支付" width="400px">
      <div class="pay-info">
        <p><strong>订单号：</strong>{{ order?.id }}</p>
        <p><strong>支付金额：</strong>¥{{ order?.totalPrice }}</p>
        <p><strong>拍摄套餐：</strong>{{ order?.packageName }}</p>
      </div>
      <template #footer>
        <el-button @click="payDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPay" :loading="payLoading">
          确认支付
        </el-button>
      </template>
    </el-dialog>

    <!-- 评价对话框 -->
    <el-dialog v-model="rateDialogVisible" title="评价订单" width="500px">
      <el-form :model="rateForm" label-width="80px">
        <el-form-item label="评分">
          <el-rate v-model="rateForm.rating" />
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input 
            v-model="rateForm.comment" 
            type="textarea" 
            :rows="4"
            placeholder="请分享您的拍摄体验..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRate" :loading="rateLoading">
          提交评价
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import api from '../utils/api'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

interface Photographer {
  id: number;
  name: string;
  style: string;
  phone: string;
  avatar: string;
  // ... 其他字段
}

interface Order {
  id: number;
  status: string;
  packageName: string;
  shootingTime: string;
  shootingLocation: string;
  totalPrice: number;
  createTime: string;
  photographer: Photographer;
  // ... 其他字段
}

const order = ref<Order | null>(null)
const payDialogVisible = ref(false)
const payLoading = ref(false)
const rateDialogVisible = ref(false)
const rateLoading = ref(false)
const completeLoading = ref(false)
const isPhotographer = ref(false)

const rateForm = reactive({
  rating: 5,
  comment: ''
})

// 获取订单详情
const fetchOrderDetail = async (orderId: number) => {
  const res = await api.get(`/orders/${orderId}`)
  order.value = res.data.order;
  if (order.value) {
    order.value.photographer = res.data.photographer;
  }
}

// 获取状态步骤
const getStatusStep = (status: string) => {
  const statusMap = {
    'PENDING': 0,
    'CONFIRMED': 2,
    'IN_PROGRESS': 3,
    'COMPLETED': 4,
    'CANCELED': -1,
    'FAILED': -1
  }
  return statusMap[status as keyof typeof statusMap] ?? 0
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap = {
    'PENDING': 'warning',
    'CONFIRMED': 'primary',
    'IN_PROGRESS': 'success',
    'COMPLETED': 'success',
    'CANCELED': 'info',
    'FAILED': 'danger'
  }
  return statusMap[status as keyof typeof statusMap] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    'PENDING': '待支付',
    'CONFIRMED': '已确认',
    'IN_PROGRESS': '拍摄中',
    'COMPLETED': '已完成',
    'CANCELED': '已取消',
    'FAILED': '已失败'
  }
  return statusMap[status as keyof typeof statusMap] || '未知状态'
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm')
}

// 支付处理
const handlePay = () => {
  payDialogVisible.value = true
}

// 确认支付
const confirmPay = async () => {
  try {
    payLoading.value = true
    // 这里应该调用支付API
    // await api.post(`/api/orders/${order.value.id}/pay`)
    
    ElMessage.success('支付成功！')
    payDialogVisible.value = false
    fetchOrderDetail(order.value!.id) // 刷新订单详情
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败，请重试')
  } finally {
    payLoading.value = false
  }
}

// 取消订单
const cancelOrder = async () => {
  if (!userStore.user) {
    ElMessage.error('请先登录');
    router.push({ name: 'login' })
    return;
  }
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用后端取消订单接口
    await api.put(`/orders/${order.value!.id}/cancel?userId=${userStore.user.id}`, {})

    ElMessage.success('订单已取消')
    fetchOrderDetail(order.value!.id) // 刷新订单详情
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败，请重试')
    }
  }
}

// 开始聊天
const startChat = (orderId: number) => {
  router.push(`/chat/${orderId}`)
}

// 查看照片
const viewPhotos = () => {
  ElMessage.info('查看照片功能开发中...')
}

// 完成订单
const completeOrder = async () => {
  if (!userStore.user) {
    ElMessage.error('请先登录');
    router.push({ name: 'login' })
    return;
  }
  try {
    completeLoading.value = true
    // 调用后端完成订单接口
    await api.put(`/orders/${order.value!.id}/complete`, {})

    ElMessage.success('订单已完成')
    fetchOrderDetail(order.value!.id) // 刷新订单详情
  } catch (error) {
    console.error('完成订单失败:', error)
    ElMessage.error('完成订单失败，请重试')
  } finally {
    completeLoading.value = false
  }
}

// 评价订单
const rateOrder = () => {
  rateDialogVisible.value = true
}

// 提交评价
const submitRate = async () => {
  if (!rateForm.comment.trim()) {
    ElMessage.warning('请填写评价内容')
    return
  }
  
  try {
    rateLoading.value = true
    // 这里应该调用评价API
    // await api.post(`/api/orders/${order.value.id}/rate`, rateForm)
    
    ElMessage.success('评价提交成功！')
    rateDialogVisible.value = false
  } catch (error) {
    console.error('评价提交失败:', error)
    ElMessage.error('评价提交失败，请重试')
  } finally {
    rateLoading.value = false
  }
}

onMounted(() => {
  // 兼容路由参数名为 id
  const orderId = Number(route.params.id);
  console.log('route.params:', route.params, 'orderId:', orderId);
  if (!orderId) {
    ElMessage.error('订单ID无效');
    // 跳转到订单列表，路由 name 应为 'orders'
    router.push({ name: 'orders' });
    return;
  }
  fetchOrderDetail(orderId);
})

onUnmounted(() => {
})
</script>

<style scoped>
.order-detail {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0;
  color: #333;
}

.order-card {
  margin-bottom: 30px;
}

.order-status {
  margin-bottom: 40px;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.order-info {
  margin-bottom: 40px;
}

.order-info h3 {
  margin-bottom: 20px;
  color: #333;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.info-item .label {
  width: 100px;
  color: #666;
  font-weight: bold;
}

.info-item .value {
  color: #333;
}

.info-item .price {
  color: #e74c3c;
  font-size: 1.2rem;
  font-weight: bold;
}

.photographer-card {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  background: #f9f9f9;
}

.photographer-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.photographer-info h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.photographer-info p {
  margin: 0 0 5px 0;
  color: #666;
}

.order-actions {
  border-top: 1px solid #eee;
  padding-top: 30px;
}

.order-actions h3 {
  margin-bottom: 20px;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.pay-info p {
  margin-bottom: 10px;
  color: #666;
}

.pay-info strong {
  color: #333;
}
</style> 